package com.demo.user.util.page;

import com.github.pagehelper.Page;
import com.google.common.base.CaseFormat;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

@Data
public class BasePageReq extends DataTablesRequestDto {

    private static final long serialVersionUID = 2806393283886713659L;
    /**
     * 默认分页大小
     */
    private static final Integer DEFAULT_PAGE_SIZE = 10;

    private String entCode;

    private String keyword;

    /**
     * 所在页数
     */
    private Integer currentPage;

    /**
     * 每页大小
     */
    private Integer pageSize;

    private Integer offset;

    private Integer limit;

    /**
     * 排序字段
     */
    private String orderBy;

    private String userCode;

    /**
     * 排序方式 ASC,DESC
     */
    private String sort;


    public String getOrderBy() {
        return orderBy;
    }

    public BasePageReq setOrderBy(String orderBy) {
        if (StringUtils.isNotBlank(orderBy)) {
            this.orderBy = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, orderBy);
        }
        return this;
    }

    public String getSort() {
        return sort;
    }

    public BasePageReq setSort(String sort) {
        this.sort = sort;
        return this;
    }

    public Integer getCurrentPage() {
        if (currentPage == null) {
            currentPage = 1;
        }
        return currentPage;
    }

    public void setCurrentPage(Integer currentPage) {
        this.currentPage = currentPage;
    }

    public Integer getPageSize() {
        if (pageSize == null) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * 检查校验分页参数
     */
    public void checkPage() {
        this.setCurrentPage((this.getCurrentPage() == null || this.getCurrentPage() < 1) ? 1 : this.getCurrentPage());
        this.setPageSize((this.getPageSize() == null || this.getPageSize() < 1 ? 10 : this.getPageSize()));
    }

    /**
     * 获取分页对象
     */
    public Page pagination() {
        checkPage();
        return new Page<>(getCurrentPage(), getPageSize());
    }

    public void singleOrderBy() {
        //只支持单排序
        if (CollectionUtils.isNotEmpty(getColumns()) && CollectionUtils.isNotEmpty(getOrder())) {
            setOrderBy(toPageParam().getOrderBy() + " " + toPageParam().getOrder());
        }
    }
}
